package com.zzy.base.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zzy.base.convert.MyGsonConverterFactory;
import com.zzy.base.gson.DoubleDefault0Adapter;
import com.zzy.base.gson.IntegerDefault0Adapter;
import com.zzy.base.gson.LongDefault0Adapter;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RetrofitManager {
    public final String HOST="https://www.wanandroid.com";


    private static OkHttpClient okHttpClient;
    private static RetrofitManager sRetrofitManager;
    private static Gson gson;
    public static RetrofitManager getInstance() {
        if (sRetrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (sRetrofitManager == null) {
                    sRetrofitManager = new RetrofitManager();
                }
            }
        }
        return sRetrofitManager;
    }
    private RetrofitManager() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15,TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
//                .cookieJar(cookieJar)
//                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
//                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
//                .addInterceptor(InterceptorUtil.logInterceptor())
//                .addInterceptor(InterceptorUtil.headerInterceptor())
                .build();

    }

    public <T> T getApiService(Class<T> tClass){
        return new Retrofit.Builder()
                .baseUrl(HOST)
                .addConverterFactory(MyGsonConverterFactory.create(buildGson()))//添加json自定义（根据需求）
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
                .create(tClass);
    }
    public static Gson buildGson() {
        if (gson == null) {
            gson = new GsonBuilder()
                    .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                    .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                    .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                    .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                    .registerTypeAdapter(long.class, new LongDefault0Adapter())
                    .create();
        }
        return gson;
    }

}
